<?php
/**
 * app用户主动发起扣款的行为记录接口
 */
namespace App\Listeners;

use App\Events\ActiveDeductionEvent;
use App\Models\User;
use Illuminate\Queue\InteractsWithQueue;

use App\Models\RepaySummary;use Illuminate\Contracts\Queue\ShouldQueue;
use App\Models\UserBankCard;
use App\Models\RepayRecord;
use App\Models\RepayRecordMonth;
use App\Models\RepayRecordMoney;
use App\Facades\CollectionRequestFacade;
use App\Constant\QueueKey;

class ActiveDeductionEventListener implements ShouldQueue
{

    use InteractsWithQueue;

    public $queue = QueueKey::QUEUE_COLLECTION_QUEUE_TWO;


    public $timeout = 500; //秒数

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //

    }

    /**
     * Handle the event.
     *
     * @param  ActiveDeductionEvent  $event
     * @return void
     */
    public function handle(ActiveDeductionEvent $event)
    {
        $list=[];
        $recordInfo = RepayRecord::where('id',$event->record_id)
            ->first();
        if(empty($recordInfo)){
            return;
        }
        $summaryInfo = $recordInfo->relationSummary;
        //银行卡信息
        $list['caseCode'] = $summaryInfo->getCaseCode();//借款号（案件唯一标识）
        $list['applyTime'] =  strtotime($recordInfo->updated_at) * 1000;//申请时间
        $list['repayMoney'] = $this->getRepayMoney($recordInfo);//扣款金额
        $card_num = UserBankCard::where('id',$recordInfo->bank_cards_id)->value('card_num');
        $list['repayBankCard'] = $card_num;//银行卡号
        $resultInfo = $this->getResultInfo($recordInfo);
        $list['result'] = $resultInfo['result'];//扣款结果
        $list['backResult'] = $resultInfo['backResult'];//反馈结果
        $list['proposerName'] = $this->getRepayType($recordInfo->repay_type); //发起人
        $list['comments'] = '';//备注
        $result = CollectionRequestFacade::sendActiveDeductionCase($list);
        $data['result'] = $result;
        $data['activededuction'] = $event->record_id;
        \Log::debug('app用户主动发起扣款的行为记录接口:' . json_encode($data,JSON_UNESCAPED_UNICODE));
    }


    public function getRepayType($type){
        $repay_type = array(
            1 => 'APP发起',
            2 => '自动还款',
            3 => '代扣',
            4 => '销账',
            5 => '代扣',
            6 => 'APP发起2',
        );
        return $repay_type[$type];
    }

    /**
     * Description:获取用户信息
     * Author:lijiafei
     * @param $user_id int
     * @return String
     */
    public function getUserInfo($user_id)
    {
        $info = User::select('id', 'nfsp_user_id', 'source', 'phone_num')->where('id', $user_id)->first();
        $info->name = $info->real_name;
        $info->cert_number = $info->cert_no;
        return $info;
    }

    /**
     * Description:
     */
    protected function getResultInfo($recordInfo){
        if ($recordInfo->status == RepayRecord::STATUS_FOUR){
            $list['result'] = '还款成功';//扣款结果
            $list['backResult'] = '';//反馈结果
        }else {
            //判断资方
            $is_channel = RepaySummary::getLoanChannel($recordInfo->summary_id);
            if ($is_channel) {
                //新数据,老数据的晋商,新光大,有资方的
                if ($recordInfo->common->status != RepayRecord::STATUS_FOUR && $recordInfo->month->status != RepayRecordMonth::STATUS_FOUR && $recordInfo->money->status != RepayRecordMoney::STATUS_FOUR) {
                    $list['result'] = '还款失败';//扣款结果
                    $list['backResult'] = $recordInfo->failure_message;//反馈结果
                } else {
                    $list['result'] = '部分还款成功';//扣款结果
                    $list['backResult'] = $recordInfo->failure_message;//反馈结果
                }
            } else {
                $list['result'] = '还款失败';//扣款结果
                $list['backResult'] = $recordInfo->failure_message;//反馈结果
            }
        }
        return $list;
    }



    protected function getRepayMoney($recordInfo){
        $arrayMoney = RepaySummary::getYihuanMoney($recordInfo);
        if($recordInfo->period == 0){
            return bcadd(bcadd($arrayMoney['all_money'],$arrayMoney['money_repayment_money'],2),$arrayMoney['common_repayment_money'],2);
        }else{
            return $arrayMoney['all_money'];
        }
    }
}
